package com.zfl.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zfl.mapper.ArticleMapper;
import com.zfl.pojo.Article;
import com.zfl.pojo.PageBean;
import com.zfl.service.ArticleService;
import com.zfl.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

//@Service
public class ArticleSeviceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;


    @Override
    public void add(Article article) {
        long currentTime = System.currentTimeMillis();
        article.setCreateTime(currentTime);
        article.setUpdateTime(currentTime);
        Map<String, Object> map = ThreadLocalUtil.get();
        int createUser = (int) map.get("id");
        article.setCreateUser(createUser);
        articleMapper.add(article);
    }

    @Override
    public PageBean<Article> list(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
        //创建PageBean对象
        PageBean<Article> pb = new PageBean<>();
        //开启分页查询PageHelper
        PageHelper.startPage(pageNum, pageSize);
        //调用Mapper
        Map<String, Object> map = ThreadLocalUtil.get();
        int createUser = (int) map.get("id");
        List<Article> articles = articleMapper.list(createUser, categoryId, state);
        //Page中提供了方法,可以获取PageHelper分页查询后,得到的都总条数和当前页数据
        Page<Article> p = (Page<Article>) articles;
        //数据填充到PageBean
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return pb;
    }

    @Override
    public Article detail(int id) {
        return articleMapper.detail(id);
    }

    @Override
    public void delete(int id) {
        articleMapper.delete(id);
    }

    @Override
    public void upadte(Article article) {
        article.setUpdateTime(System.currentTimeMillis());
        articleMapper.update(article);
    }
}
